#include "qhostfactory.h"
#include <QDebug>
#include "host/qabstracthost.h"
#include "host/qformhost.h"
#include "xmlobject.h"

QMap<QString, tagHostInfo*> QHostFactory::m_host_map;

QHostFactory::QHostFactory()
{
}

void QHostFactory::registerHost(const QString id, QString icon, QString name, QString group,QString svgCode, const QMetaObject *host)
{
    tagHostInfo *info = m_host_map.value(id);
    if(info == NULL) {
        info = new tagHostInfo;
    }
    info->m_host_meta_object = host;
    info->m_id = id;
    info->m_icon = icon;
    info->m_name = name;
    info->m_group = group;
    info->m_svgCode  = svgCode;
    m_host_map.insert(id, info);
    qDebug() << "QHostFactory::registerHost" <<id;
}

QAbstractHost* QHostFactory::createHost(const QString id)
{
    QAbstractHost* pHostObj = NULL;
    qDebug() << "QHostFactory::createHost **************************id:" << id;
    qDebug() << "QHostFactory::createHost **************************m_host_map:" << m_host_map;
    if(id == FORM_TITLE) {
        qDebug() << "QHostFactory::createHost **************************create form:" << FORM_TITLE;
        pHostObj = new QFormHost;
        pHostObj->setAttribute(HOST_TYPE, FORM_TITLE);
        pHostObj->init();
    } else {
        tagHostInfo *info = m_host_map.value(id);
        qDebug() << "QHostFactory::createHost **************************info:" << info;
        if(info == NULL) {
            return NULL;
        }
        const QMetaObject* pObj = info->m_host_meta_object;
        if(pObj != NULL) {
            pHostObj = (QAbstractHost*)pObj->newInstance();
            pHostObj->setProperty("svgcode",info->m_svgCode);
            pHostObj->setAttribute(HOST_TYPE, id);
            pHostObj->init();
            pHostObj->initWidgetObject();
        }
    }

    return pHostObj;
}

QMap<QString, tagHostInfo*> QHostFactory::getHostInfo()
{
    return m_host_map;
}

QAbstractHost* QHostFactory::createHost(XMLObject *xml)
{
    if(xml == NULL) {
        return NULL;
    }

    QAbstractHost* pHostObj = NULL;
    qDebug() << "QHostFactory::createHost:obj Xml->" << xml->getXml();

    if(xml->getTagName() == FORM_TITLE) {
        qDebug() << "QHostFactory::createHost:new form host->" << xml->getTagName();
        pHostObj = new QFormHost;
        pHostObj->init();
        pHostObj->fromObject(xml);
        pHostObj->initWidgetObject();
        pHostObj->setAttribute(HOST_TYPE, FORM_TITLE);
    } else {
        pHostObj = createHost(xml->getProperty(HOST_TYPE));
        if(pHostObj != NULL) {
            pHostObj->fromObject(xml);
            pHostObj->initWidgetObject();
        }
    }
    return pHostObj;
}

tagHostInfo* QHostFactory::getHostInfo(const QString id)
{
    return m_host_map.value(id);
}
